package com.briup.smart.impl.server;

import com.briup.smart.env.entity.Environment;
import com.briup.smart.env.server.Server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Collection;
import java.util.LinkedList;

public class ServerImpl implements Server {
    // 判断服务器的关闭状态
    private boolean isStop;
    private ServerSocket serverSocket;
    private int port = 8888;

    @Override
    public void receive() throws Exception {
        serverSocket = new ServerSocket(port);
        System.out.println("服务器已经启动，正在监听端口："+port);
        while (!isStop) {
            Socket accept = serverSocket.accept();
            // 开启线程来处理socket
            Thread t1 = new Thread(() -> {
                Socket socket = accept;
                try (ObjectInputStream ois = new ObjectInputStream(
                        socket.getInputStream());){
                    // 从socket里获取数据
                    Object o = ois.readObject();
                    // 安全转换成environment集合
                    Collection<Environment> list = new LinkedList<>();
                    if(o instanceof Collection<?> coll){
                        for(Object obj:coll){
                            if(obj instanceof Environment e){
                                list.add(e);
                            }
                        }
                    }
                    // 输出一下接收到的数据
                    list.forEach(System.out::println);
                    System.out.println("服务器共采集："+ list.size()+"条数据");

                    // 下一步，交给入库模块插到数据库里
                    new DbStoreImpl().saveDB(list);

                } catch (Exception e) {
                    throw new RuntimeException(e);
                } finally {
                    if(socket != null){
                        try {
                            socket.close();
                        } catch (IOException e) {
                            throw new RuntimeException(e);
                        }
                    }
                }
            });
            t1.start();
            System.out.println("正在处理"+accept+"的发送请求");
        }
    }

    @Override
    public void shutdown() throws Exception {
        isStop = true;
        System.out.println("服务器正在关闭...");
        if(serverSocket != null){
            serverSocket.close();
        }
        System.out.println("服务器已经关闭，shutdown执行完毕！");
    }
}
